/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * NewJPanel.java
 *
 * Created on 2009/02/04, 12:28:18
 */

package com.anatanokeitai;


import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.StyleSheet;
import org.netbeans.api.project.Project;
import org.netbeans.api.project.ProjectInformation;
import org.netbeans.api.project.ProjectUtils;
import org.netbeans.api.project.ui.OpenProjects;
import org.openide.DialogDescriptor;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.filesystems.FileLock;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.Repository;
import org.openide.util.Exceptions;


/**
 *
 * @author ysakurai
 */
public class ToolbarPanel extends javax.swing.JPanel {

    /** Creates new form NewJPanel */
    public ToolbarPanel() {
        initComponents();
        PropertyChangeListener listener = new PropertyChangeListener() {

            public void propertyChange(PropertyChangeEvent evt) {
                
                jComboBox1.setModel(getItems());

            }
        };
        OpenProjects.getDefault().addPropertyChangeListener(listener);
    }

    private final static String No_J2MEProjects_Found = "No J2MEProjects Found";


    private javax.swing.DefaultComboBoxModel getItems(){
        OpenProjects op = OpenProjects.getDefault();
        Project[] projects = op.getOpenProjects();
        StringBuffer sb = new StringBuffer();
        for (int i=0;i<projects.length;i++){
/*
            FileObject fo = projects[i].getProjectDirectory();
            FileObject[] children1 = fo.getChildren();
            
            //System.out.println("children1.length:"+children1.length);

            for (int j=0;j<children1.length;j++){

                boolean existsJar = false;
                boolean existsJad = false;
                
                if(children1[j].getName().equals("dist")){
                    FileObject[] children2 = children1[j].getChildren();
                    //System.out.println("children2.length:"+children2.length);
                    for (int k=0;k<children2.length;k++){
                        System.out.println("\t"+children2[k].getNameExt().toLowerCase());
                        if (children2[k].getNameExt().toLowerCase().endsWith(".jar"))existsJar=true;
                        if (children2[k].getNameExt().toLowerCase().endsWith(".jad"))existsJad=true;
                    }
                }
                
                if(existsJad&&existsJar){
                    ProjectInformation info = ProjectUtils.getInformation(projects[i]);
                    sb.append(info.getDisplayName()+"\n");

                }
            }
*/
            //projects[i].getClass().
            //System.out.println(projects[i].getClass().getName());
            //System.out.println(projects[i].getClass().getCanonicalName());
            if(projects[i].getClass().getName().equals("org.netbeans.modules.mobility.project.J2MEProject")){
                ProjectInformation info = ProjectUtils.getInformation(projects[i]);
                sb.append(info.getDisplayName()+"\n");
            }

        }
        if (sb.toString().length()==0){
            return new javax.swing.DefaultComboBoxModel(new String[]{No_J2MEProjects_Found});
        }else{
            return new javax.swing.DefaultComboBoxModel(sb.toString().split("\n"));
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jComboBox1 = new javax.swing.JComboBox();
        jButton1 = new javax.swing.JButton();

        setMaximumSize(new java.awt.Dimension(216, 43));
        setMinimumSize(new java.awt.Dimension(216, 43));

        jComboBox1.setModel(getItems());

        jButton1.setText(org.openide.util.NbBundle.getMessage(ToolbarPanel.class, "ToolbarPanel.jButton1.text_1")); // NOI18N
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addComponent(jComboBox1, 0, 160, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton1))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
        // TODO add your handling code here:
        if(jComboBox1.getSelectedItem().toString().equals(No_J2MEProjects_Found)){
            NotifyDescriptor nd = new NotifyDescriptor.Message(No_J2MEProjects_Found,NotifyDescriptor.INFORMATION_MESSAGE);
            DialogDisplayer.getDefault().notify(nd);
            return;
        }else{
            byte[] jadData=null;
            String jadName=null;
            byte[] jarData=null;
            String jarName=null;

            Project project=null;
            Project[] projects = OpenProjects.getDefault().getOpenProjects();
            for (int i=0;i<projects.length;i++){
                if(projects[i].getClass().getName().equals("org.netbeans.modules.mobility.project.J2MEProject")&&ProjectUtils.getInformation(projects[i]).getDisplayName().equals(jComboBox1.getSelectedItem().toString())){
                    project = projects[i];
                }
            }

            if(project==null){
                return;
            }

            FileObject[] children1 = project.getProjectDirectory().getChildren();
            for (int i=0;i<children1.length;i++){

                if(children1[i].getName().equals("dist")){
                    FileObject[] children2 = children1[i].getChildren();
                    //System.out.println("children2.length:"+children2.length);
                    for (int j=0;j<children2.length;j++){
                        System.out.println("\t"+children2[j].getNameExt().toLowerCase());
                        if (children2[j].getNameExt().toLowerCase().endsWith(".jar")){
                            jarName = children2[j].getExt();
                            try {
                                BufferedInputStream bis = new BufferedInputStream(children2[j].getInputStream());
                                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                byte[] buff = new byte[10240];
                                int read;
                                while((read=bis.read(buff))!=-1){
                                    baos.write(buff, 0, read);
                                }
                                jarData = baos.toByteArray();
                                baos.close();
                            } catch (IOException ex) {
                                Exceptions.printStackTrace(ex);
                            }
                        }
                        if (children2[j].getNameExt().toLowerCase().endsWith(".jad")){
                            jadName = children2[j].getNameExt();
                            try {
                                BufferedInputStream bis = new BufferedInputStream(children2[j].getInputStream());
                                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                byte[] buff = new byte[10240];
                                int read;
                                while((read=bis.read(buff))!=-1){
                                    baos.write(buff, 0, read);
                                }
                                jadData = baos.toByteArray();
                                baos.close();
                            } catch (IOException ex) {
                                Exceptions.printStackTrace(ex);
                            }
                        }
                    }
                }

            }
            if(jadName==null||jadData==null||jarName==null||jarData==null){
                NotifyDescriptor nd = new NotifyDescriptor.Message("jar or jad file not found.\n[1st] build project\n[2nd] push \"UP\" button",NotifyDescriptor.ERROR_MESSAGE);
                DialogDisplayer.getDefault().notify(nd);
                return;
            }

            String configFilename = "SappliUploaderForAppliget.cfg";
            UsernameAndPasswordPanel panel = new UsernameAndPasswordPanel();

            FileObject root = Repository.getDefault().getDefaultFileSystem().getRoot();
            //System.out.println(root.getName());
            FileObject configFile = root.getFileObject(configFilename);
            if(configFile!=null&&!configFile.isFolder()){
                try {
                    InputStream is = configFile.getInputStream();
                    Properties proprerties = new Properties();
                    proprerties.loadFromXML(is);
                    is.close();
                    panel.setUsername(proprerties.getProperty("username"));
                    panel.setPassword(proprerties.getProperty("password"));
                    panel.enableSaveOption();
                } catch (IOException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }

            DialogDescriptor dd = new DialogDescriptor(panel,"Appliget Username and Password",true,NotifyDescriptor.OK_CANCEL_OPTION,NotifyDescriptor.OK_OPTION,null);
            Object pushed = DialogDisplayer.getDefault().notify(dd);
            if(pushed==NotifyDescriptor.OK_OPTION){
                Properties proprerties = new Properties();
                proprerties.put("username", panel.getUsername());
                proprerties.put("password", panel.getPassword());

                if(panel.isEnabledSaveOption()){
                    if(configFile==null){
                        try {
                            configFile = root.createData(configFilename);
                        } catch (IOException ex) {
                            Exceptions.printStackTrace(ex);
                        }
                    }
                    if(configFile!=null&&!configFile.isFolder()){
                        try {
                            FileLock lock = configFile.lock();
                            OutputStream os = configFile.getOutputStream(lock);
                            proprerties.storeToXML(os, "Appliget Username and Password");
                            os.close();
                        } catch (IOException ex) {
                            Exceptions.printStackTrace(ex);
                        }

                    }
                }


                URL url;
                URLConnection urlc;

                try {
                    String auth = "Basic "+Base64.encode((panel.getUsername()+":"+panel.getPassword()).getBytes());
                    url = new URL("http://ac-admin.appget.com/member/v-upload/upload/index.htm");
                    urlc = url.openConnection();
                    urlc.setDoInput(true);
                    urlc.setDoOutput(false);
                    urlc.addRequestProperty("Referer", "http://ac-admin.appget.com/member/index.php");
                    urlc.addRequestProperty("Authorization", auth);
                    InputStream is = urlc.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    String line;
                    while((line=br.readLine())!=null){
                        //System.out.println(line);
                    }
                    br.close();
                    String cookie1 = urlc.getHeaderField("Set-Cookie");
                    String jsessionid1 = cookie1.substring(cookie1.indexOf("JSESSIONID=")+"JSESSIONID=".length(), cookie1.indexOf(";"));
                    //System.out.println(cookie);
                    //System.out.println(jsessionid);
                    cookie1 = cookie1.split(";")[0];

                    url = new URL("http://ac-admin.appget.com/member/v-upload/upload/confirm.do;jsessionid="+jsessionid1);
                    urlc = url.openConnection();
                    urlc.setDoInput(true);
                    urlc.setDoOutput(true);
                    urlc.addRequestProperty("Referer", "http://ac-admin.appget.com/member/v-upload/upload/index.htm");
                    urlc.addRequestProperty("Content-Type", "multipart/form-data; boundary=---------------------------7d932c2b05ee");
                    urlc.addRequestProperty("Cookie", cookie1);
                    urlc.addRequestProperty("Authorization", auth);

                    BufferedOutputStream bos = new BufferedOutputStream(urlc.getOutputStream());
                    bos.write("-----------------------------7d932c2b05ee\r\n".getBytes());
                    bos.write("Content-Disposition: form-data; name=\"jadFile\"; filename=\"".getBytes());
                    bos.write(jadName.getBytes());
                    bos.write("\"\r\n".getBytes());
                    bos.write("Content-Type: text/plain\r\n\r\n".getBytes());
                    bos.write(jadData);
                    bos.write("\r\n".getBytes());
                    bos.write("-----------------------------7d932c2b05ee\r\n".getBytes());
                    bos.write("Content-Disposition: form-data; name=\"jarFile\"; filename=\"".getBytes());
                    bos.write(jarName.getBytes());
                    bos.write("\"\r\n".getBytes());
                    bos.write("Content-Type: application/x-zip-compressed\r\n\r\n".getBytes());
                    bos.write(jarData);
                    bos.write("\r\n".getBytes());
                    bos.write("-----------------------------7d932c2b05ee--\r\n".getBytes());
                    bos.close();

                    is = urlc.getInputStream();
                    br = new BufferedReader(new InputStreamReader(is));
                    String fsessionid=null;
                    StringBuffer sb = new StringBuffer();
                    while((line=br.readLine())!=null){
                        sb.append(line+"\n");
                        if(line.indexOf("fsessionid\" value=\"")!=-1){
                            fsessionid = line.substring(line.indexOf("fsessionid\" value=\"")+"fsessionid\" value=\"".length(), line.indexOf("\">"));
                        }
                    }
                    //System.out.println(sb.toString());
                    //System.out.println("fsessionid:"+fsessionid);
                    StyleSheet sheet = new StyleSheet();
                    sheet.importStyleSheet(new URL("http://ac-admin.appget.com/css/dev_import.css"));

                    if(fsessionid==null){
                        JEditorPane htmlPane = new JEditorPane();
                    	htmlPane.setEditable(false);
                        htmlPane.setContentType("text/html");
                        htmlPane.read(new ByteArrayInputStream(sb.toString().getBytes()),new HTMLDocument(sheet));
                        //JFrame frame = new JFrame();
                        //frame.add(htmlPane);
                        //frame.setVisible(true);
                        dd = new DialogDescriptor(htmlPane,"Sappli Uploader For Appliget",true,NotifyDescriptor.DEFAULT_OPTION,NotifyDescriptor.OK_OPTION,null);
                        DialogDisplayer.getDefault().notify(dd);
                        return;
                    }
                    br.close();
                    String cookie2 = urlc.getHeaderField("Set-Cookie");
                    String jsessionid2 = cookie2.substring(cookie2.indexOf("JSESSIONID=")+"JSESSIONID=".length(), cookie2.indexOf(";"));
                    cookie2 = cookie2.split(";")[0];


                    url = new URL("http://ac-admin.appget.com/member/v-upload/upload/result.do");
                    urlc = url.openConnection();
                    urlc.setDoInput(true);
                    urlc.setDoOutput(true);
                    urlc.addRequestProperty("Referer", "http://ac-admin.appget.com/member/v-upload/upload/confirm.do;jsessionid="+jsessionid1);
                    
                    urlc.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    urlc.addRequestProperty("Cookie", cookie2);
                    urlc.addRequestProperty("Authorization", auth);

                    bos = new BufferedOutputStream(urlc.getOutputStream());
                    bos.write("fsessionid=".getBytes());
                    bos.write(fsessionid.getBytes());
                    //bos.write("\r\n\r\n".getBytes());
                    bos.close();

                    is = urlc.getInputStream();
                    br = new BufferedReader(new InputStreamReader(is));
                    sb = new StringBuffer();
                    while((line=br.readLine())!=null){
                        sb.append(line+"\n");
                    }
                    //System.out.println(sb.toString());

                    JEditorPane htmlPane = new JEditorPane();
                 	htmlPane.setEditable(false);
                    htmlPane.setContentType("text/html");
                    htmlPane.read(new ByteArrayInputStream(sb.toString().getBytes()),new HTMLDocument(sheet));
                    dd = new DialogDescriptor(htmlPane,"Sappli Uploader For Appliget",true,NotifyDescriptor.DEFAULT_OPTION,NotifyDescriptor.OK_OPTION,null);
                    DialogDisplayer.getDefault().notify(dd);
                    //JFrame frame = new JFrame();
                    //frame.add(htmlPane);
                    //frame.setVisible(true);


                } catch (IOException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
        }


    }//GEN-LAST:event_jButton1MouseClicked


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration//GEN-END:variables

}
